package com.zxb.core.log;

import java.lang.reflect.Method;

import com.zxb.core.common.Req;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author Zxb
 */
@Aspect
@Component
@Slf4j
public class LogSpendAspect {

	private final ThreadLocal<Long> stimeLocal = new ThreadLocal<>();

    @Pointcut("@annotation(com.zxb.core.log.LogSpend)")
    public void pointCut(){}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogSpend ann = method.getAnnotation(LogSpend.class);
        if (ann!=null){
            stimeLocal.set(System.currentTimeMillis());
        }
    }

    @After("pointCut()")
    public void after(JoinPoint joinPoint){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogSpend ann = method.getAnnotation(LogSpend.class);
        if (ann!=null){
        	long stime = stimeLocal.get();
            long etime = System.currentTimeMillis();
            long spend = etime-stime;

            String uri = Req.getURI();
            log.info("request {}, spend {}", uri, spend);
        }
        stimeLocal.remove();
    }
}
